package com.yanqu.road.server.manger.activity.feast;

import com.yanqu.road.dao.impl.activity.feast.FeastConfigDaoImpl;
import com.yanqu.road.dao.impl.activity.feast.FeastUserMountAllotDataDaoImpl;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.feast.config.ShanHeFeastConfig;
import com.yanqu.road.entity.activity.feast.data.FeastUserMountAllotData;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.pb.activity.ShanHeFeastProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.feast.ShanHeFeastModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.YanQuMessageUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class ShanHeFeastMgr extends TempMgr {

    private static ShanHeFeastConfig config = null;

    private static RandomHelper randomHelper = new RandomHelper();
    // 宗门使用的体力
    private static long sectTotalEnergy = 0;
    // 玩家分配灵峰
    private static Map<Long, FeastUserMountAllotData> userMountAllotMap = new ConcurrentHashMap<>();

    /**
     * 重新加载活动
     */
    public static void reloadActivityData() {
        getLogger().info("reload Shan He Feast start");
        List<ActivityInfo> list = NormalActivityMgr.getOpenActivityInfoList(eActivityType.Feast.getValue());
        if (list.isEmpty()) {
            config = null;
            userMountAllotMap.clear();
            sectTotalEnergy = 0;
            getLogger().info("reload Shan He Feast end, no activity in show time.");
            return;
        }
        ActivityInfo activityInfo = list.get(0);

        loadConfigFromDb(activityInfo);
        getLogger().info("reload Shan He Feast end, activityId {}.", config.getActivityInfo().getActivityId());

        // 加载用户灵峰数据
        userMountAllotMap = new FeastUserMountAllotDataDaoImpl().getFeastUserMountAllotData(config.getActivityInfo().getActivityId());
        // 重置
        sectTotalEnergy = 0;

        for (GamePlayer player : GamePlayerMgr.getAllOnlinePlayer()) {
            player.getModule(ShanHeFeastModule.class).feastLogin();
        }
    }

    public static void offLine(GamePlayer player) {
        ActivityInfo activityInfo = getActivityInfo();
        if (activityInfo == null) {
            return;
        }
        if (!ActivityMgr.activityInShowTime(activityInfo)) {
            return;
        }
        // 离线通知跨服
        ShanHeFeastProto.CrossFeastLeavePlaceReqMsg.Builder reqMsg = ShanHeFeastProto.CrossFeastLeavePlaceReqMsg.newBuilder();
        reqMsg.setActivityId(activityInfo.getActivityId());
        player.sendPacket(CrossProtocol.C_CROSS_SHAN_HE_FEAST_OFF_LINE, reqMsg);
    }

    /**
     * 数据库加载配置
     */
    private static void loadConfigFromDb(ActivityInfo activityInfo) {
        Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(activityInfo.getActivityId());
        ShanHeFeastConfig tmpConfig = new ShanHeFeastConfig();
        tmpConfig.setActivityInfo(activityInfo);
        FeastConfigDaoImpl configDao = new FeastConfigDaoImpl();
        tmpConfig.setPlaceConfigMap(configDao.getFeastPvpPlaceConfigMap(activityInfo.getActivityId()));
        // 初始化配置
        tmpConfig.initConfig(activityConfigMap);
        tmpConfig.setEquipmentConfigMap(configDao.getFeastEquipmentConfigMap(activityInfo.getActivityId()));
        tmpConfig.setEventConfigMap(configDao.getFeastEventConfigMap(activityInfo.getActivityId()));
        tmpConfig.setMissionConfigMap(configDao.getFeastMissionMap(activityInfo.getActivityId()));
        tmpConfig.setStateConfigMap(configDao.getFeastStateConfigMap(activityInfo.getActivityId()));
        tmpConfig.setTripodConfigMap(configDao.getFeastTripodConfigMap(activityInfo.getActivityId()));
        tmpConfig.setNpcConfigMap(configDao.getFeastNpcConfigMap(activityInfo.getActivityId()));
        tmpConfig.setUpgradeConfigMap(configDao.getFeastUpgradeConfigMap(activityInfo.getActivityId()));
        config = tmpConfig;

    }

    public static ShanHeFeastConfig getConfig() {
        return config;
    }

    /**
     * 活动信息
     */
    public static ActivityInfo getActivityInfo() {
        return config == null ? null : config.getActivityInfo();
    }

    public static long getSectTotalEnergy() {
        return sectTotalEnergy;
    }

    public static void setSectTotalEnergy(long sectTotalEnergy) {
        ShanHeFeastMgr.sectTotalEnergy = sectTotalEnergy;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    /**
     * 获取并初始化用户灵峰分配数据
     */
    public static FeastUserMountAllotData getUserMountData(long userId) {
        if (userId == 0) {
            return null;
        }
        // 不存在则初始化
        if (!userMountAllotMap.containsKey(userId)) {
            synchronized (userMountAllotMap) {
                if (!userMountAllotMap.containsKey(userId)) {
                    FeastUserMountAllotData userMountAllotData = new FeastUserMountAllotData();
                    userMountAllotData.setActivityId(getActivityInfo().getActivityId());
                    userMountAllotData.setUserId(userId);
                    userMountAllotData.setInsertOption();
                    userMountAllotMap.put(userId, userMountAllotData);
                }
            }
        }
        return userMountAllotMap.get(userId);
    }

    @Override
    public boolean save() {
        if (userMountAllotMap != null) {
            for (FeastUserMountAllotData userMountAllotData : userMountAllotMap.values()) {
                if (userMountAllotData.isInsertOption()) {
                    new FeastUserMountAllotDataDaoImpl().add(userMountAllotData);
                } else if (userMountAllotData.isUpdateOption()) {
                    new FeastUserMountAllotDataDaoImpl().update(userMountAllotData);
                }
            }
        }
        return true;
    }


    /**
     * 获取分配时间
     */
    public static long getHistoryAllotTime(long historyTime) {
        int allotCount = (int)Math.floor((double)(historyTime - config.getActivityInfo().getBeginTime()) / config.getFEAST_PEAK_ASSIGN_CD());
        // 当前的
        long tempAllotTimeId = config.getActivityInfo().getBeginTime() + allotCount * config.getFEAST_PEAK_ASSIGN_CD();
        if (tempAllotTimeId < config.getActivityInfo().getBeginTime()) {
            tempAllotTimeId = config.getActivityInfo().getBeginTime();
        }
        return tempAllotTimeId;
    }

    /**
     * 同步灵峰分配
     * */
    public static void syncMountAllot(ShanHeFeastProto.CrossFeastSyncAllotMountMsg reqMsg) {
        // 确认收到
        ActivityInfo activityInfo = getActivityInfo();
        if (activityInfo == null || activityInfo.getActivityId() != reqMsg.getActivityId()) {
            return;
        }
        long allotTime = reqMsg.getCurAllotTime();
        synchronized (userMountAllotMap) {
            // 更新数据
            Set<Long> hasMountUserIdSet = new HashSet<>();
            for (ShanHeFeastProto.FeastUserMountAllotInfoTemp allotInfoTemp : reqMsg.getUserAllotListList()) {
                long userId = allotInfoTemp.getUserId();
                int mountId = allotInfoTemp.getMountId();
                FeastUserMountAllotData userMountAllotData = getUserMountData(userId);
                if (userMountAllotData == null) {
                    continue;
                }
                hasMountUserIdSet.add(userId);
                Map<Long, Integer> userMountInfoDataMap = userMountAllotData.getUserMountMap();
                userMountInfoDataMap.put(allotTime, mountId);
                userMountAllotData.setUserMountMap(userMountInfoDataMap);
            }
            // 更新没有灵峰的玩家
            int defaultMountId = 10000;
            for (FeastUserMountAllotData userMountAllotData : userMountAllotMap.values()) {
                if (hasMountUserIdSet.contains(userMountAllotData.getUserId())) {
                    continue;
                }
                Map<Long, Integer> userMountInfoDataMap = userMountAllotData.getUserMountMap();
                userMountInfoDataMap.put(allotTime, defaultMountId);
                userMountAllotData.setUserMountMap(userMountInfoDataMap);
            }

            ShanHeFeastProto.CrossFeastAckAllotMountMsg.Builder builder = ShanHeFeastProto.CrossFeastAckAllotMountMsg.newBuilder();
            builder.setCurAllotTime(allotTime);
            builder.setActivityId(activityInfo.getActivityId());
            GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_SHAN_HE_FEAST_ACK_CAMP_ENERGY, builder));
        }
    }
}
